package com.fish.anne.webapp.action.front;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.util.AlipayParameter;
import com.alipay.util.CheckURL;
import com.fish.anne.model.Auto;
import com.fish.anne.model.Order;
import com.fish.anne.model.OrderPaymentCfg;
import com.fish.anne.model.SystemRegion;
import com.fish.anne.service.AutoManager;
import com.fish.anne.service.OrderManager;
import com.fish.anne.service.OrderPaymentCfgManager;
import com.fish.anne.service.SystemRegionManager;
import com.fish.anne.webapp.action.BaseAction;
import com.fish.anne.webapp.formbean.FrontAutoSearch;
import com.fish.anne.webapp.util.GridJsonUtil;
import com.fish.anne.webapp.util.ParseJsonUtil;
import com.opensymphony.xwork2.Preparable;

public class OrderAction extends BaseAction implements Preparable {
	private OrderManager orderManager;
	private List<Order> orders;
	private Order order;
	private Long orderId;

	private OrderPaymentCfgManager orderPaymentCfgManager;
	private SystemRegionManager systemRegionManager;
	public void setSystemRegionManager(SystemRegionManager systemRegionManager) {
		this.systemRegionManager = systemRegionManager;
	}

	public void setOrderPaymentCfgManager(OrderPaymentCfgManager orderPaymentCfgManager) {
		this.orderPaymentCfgManager = orderPaymentCfgManager;
	}

	private AutoManager autoManager;

	public void setAutoManager(AutoManager autoManager) {
		this.autoManager = autoManager;
	}

     
    private Auto auto ;
    
    public Auto getAuto() {
		return auto;
	}

	public void setAuto(Auto auto) {
		this.auto = auto;
	}

 
	
	
	public void setOrderManager(OrderManager orderManager) {
		this.orderManager = orderManager;
	}

	public List<Order> getOrders() {
		return orders;
	}

	/**
	 * Grab the entity from the database before populating with request
	 * parameters
	 */
	public void prepare() {
		if (getRequest().getMethod().equalsIgnoreCase("post")) {
			// prevent failures on new
			String orderId = getRequest().getParameter("order.orderId");
			if (orderId != null && !orderId.equals("")) {
				order = orderManager.get(new Long(orderId));
			}
		}
	}

	/**
	 * find by memberId
	 * 
	 * @return
	 */
	public String list() { 
		Long memberId = this.getLoginedMemberId();
		orders= orderManager.getOrderByUserId(memberId); 
		return SUCCESS;
	}

	public void setOrderId(Long orderId) {
		this.orderId = orderId;
	}

	public Order getOrder() {
		return order;
	}

	public void setOrder(Order order) {
		this.order = order;
	}

	public String delete() {
		orderManager.remove(orderId);
		saveMessage(getText("order.deleted"));

		return SUCCESS;
	}

	public String edit() {
		if (orderId != null) {
			order = orderManager.get(orderId);
            auto = this.autoManager.get(order.getAutoId());
		}  

		return SUCCESS;
	}

	private Long autoId;

	public Long getAutoId() {
		return autoId;
	}

	public void setAutoId(Long autoId) {
		this.autoId = autoId;
	}

	private FrontAutoSearch frontAutoSearch;

	public FrontAutoSearch getFrontAutoSearch() {
		return frontAutoSearch;
	}

	public void setFrontAutoSearch(FrontAutoSearch frontAutoSearch) {
		this.frontAutoSearch = frontAutoSearch;
	}

	public String save() throws Exception {

		if (order == null) {
			order = new Order();
		}
		boolean isNew = (order.getOrderId() == null);

		// Long mid = getLoginedMemberId();
		Long mid = 0L;
		final byte alipayTypeId = 2;
		if (isNew) {

			order.setPaymentTypeId(alipayTypeId);
			order.setCreateTime(System.currentTimeMillis());
			order.setDiscount(0);
			order.setIp("");
			order.setLastChangeTime(0L);
			order.setMemberId(mid);
			order.setOrderConfirm((byte) 0);
			order.setPayStatus((byte) 0);

			order.setSelfFlag(true);
			order.setShipEmail("");
			order.setShipEmail("");
			order.setStatus(Order.ORDER_CREATE);
			order.setTaxCompany("");

			Auto auto = this.autoManager.get(autoId);
			auto.setFrontAutoSearch(frontAutoSearch);
			order.setAutoId(autoId);
			order.setTotalAmount(auto.getTotalAmount());
			order.setFinalAmount(auto.getTotalAmount());
			order.setShipAddr("");
			order.setShipMobile("");

			order.setEndDate(this.frontAutoSearch.getEndDate());
			SystemRegion systemRegion = systemRegionManager.get(frontAutoSearch.getTo().longValue());
			order.setEndPlaceId(systemRegion == null ?"" :systemRegion.getLocalName());
			order.setStartDate(frontAutoSearch.getBeginDate());
			
			systemRegion = systemRegionManager.get(frontAutoSearch.getFrom().longValue());
			order.setStartPlaceId(systemRegion == null ?"" :systemRegion.getLocalName());
		}

		orderManager.save(order);

		String key = (isNew) ? "order.added" : "order.updated";
		saveMessage(getText(key));

		return SUCCESS;

	}

	private AlipayParameter alipayParameter;

	public AlipayParameter getAlipayParameter() {
		return alipayParameter;
	}

	public void setAlipayParameter(AlipayParameter alipayParameter) {
		this.alipayParameter = alipayParameter;
	}

	public String pay() {
		order = orderManager.get(orderId);
		OrderPaymentCfg orderPaymentCfg = orderPaymentCfgManager.get(Long.valueOf(order.getPaymentTypeId()));
		alipayParameter = AlipayParameter.initAlipayParameter(getRequest(), order, orderPaymentCfg);
		return "alipay";
	}

	@SuppressWarnings("unchecked")
	public String aliSyncCallback() throws Exception {

		HttpServletRequest request = getRequest();

		log.info("aliSyncCallback query string is " + request.getQueryString());

		orderId = Long.valueOf(request.getParameter("out_trade_no"));
		order = orderManager.get(orderId);
		OrderPaymentCfg orderPaymentCfg = orderPaymentCfgManager.get(Long.valueOf(order.getPaymentTypeId()));
		String partner = orderPaymentCfg.getPayMemberId();
		String privateKey = orderPaymentCfg.getPayPrivateKey();
		String sign = request.getParameter("sign");

		String alipayNotifyURL = "http://notify.alipay.com/trade/notify_query.do?" + "partner=" + partner + "&notify_id=" + request.getParameter("notify_id");
		String responseTxt = CheckURL.check(alipayNotifyURL);

		Map params = new HashMap();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}

		String mysign = com.alipay.util.SignatureHelper_return.sign(params, privateKey);

		if (mysign.equals(sign) && responseTxt.equals("true")) {
			String status = request.getParameter("trade_status");
			if (status.equals("TRADE_FINISHED") || status.equals("TRADE_SUCCESS")) {

				log.info("order ID " + orderId + " alipay recharge success");
				paySuccess();
				log.info("update order ID " + orderId + " pay status   success");
			}

		} else {
			log.info("order ID " + orderId + " alipay recharge fail , sign ");

		}

		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public String aliAsyncCallback() throws Exception {
		HttpServletRequest request = getRequest();
		PrintWriter out = getResponse().getWriter();

		log.info("aliAsyncCallback query string is " + request.getQueryString());

		orderId = Long.valueOf(request.getParameter("out_trade_no"));
		order = this.orderManager.get(orderId);
		OrderPaymentCfg orderPaymentCfg = this.orderPaymentCfgManager.get(Long.valueOf(order.getPaymentTypeId()));
		String partner = orderPaymentCfg.getPayMemberId();
		String privateKey = orderPaymentCfg.getPayPrivateKey();

		String alipayNotifyURL = "http://notify.alipay.com/trade/notify_query.do?" + "partner=" + partner + "&notify_id=" + request.getParameter("notify_id");

		String responseTxt = CheckURL.check(alipayNotifyURL);

		Map params = new HashMap();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}

		String mysign = com.alipay.util.SignatureHelper.sign(params, privateKey);

		if (mysign.equals(request.getParameter("sign")) && responseTxt.equals("true")) {

			String tradeStatus = request.getParameter("trade_status");
			if (tradeStatus.equals("WAIT_BUYER_PAY")) {
				// 等待买家付款
				out.println("success");
			} else if (tradeStatus.equals("TRADE_FINISHED") || tradeStatus.equals("TRADE_SUCCESS")) {

				log.info("order ID " + orderId + " alipay recharge success");
				paySuccess();
				log.info("update order ID " + orderId + "   success");

				out.println("success");

			}
		} else {

			log.info("recharge ID " + orderId + " alipay recharge fail");

			out.println("fail" + "<br>");

		}

		return SUCCESS;
	}

	private void paySuccess() {
		order.setStatus(Order.ORDER_PAY);
		orderManager.save(order);
	}

 

	public void getAllOrder() {

		Long memberId = this.getLoginedMemberId();
		List<Order> list = orderManager.getOrderByUserId(memberId);
		String json = ParseJsonUtil.list2json(list);
		try {
			HttpServletResponse response = this.getResponse();
			PrintWriter out;
			out = response.getWriter();
			out.println(json);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void getAllOrder2() {
		GridJsonUtil grid = new GridJsonUtil();
		HttpServletRequest request = this.getRequest();
		HttpServletResponse response = this.getResponse();
		final String page = request.getParameter("_page"); // 取得当前页数,注意这是jqgrid自身的参数
		String oper = request.getParameter("_oper");
		if ("del".equals(oper)) {
			String ids = request.getParameter("id");
			this.delete2(ids);
		}
		final String rows = request.getParameter("_rows"); // 取得每页显示行数，,注意这是jqgrid自身的参数
		List<Order> list = orderManager.getOrderByUserId(1l);
		int totalRecord = list.size();
		int totalPage = totalRecord % Integer.parseInt(rows) == 0 ? totalRecord / Integer.parseInt(rows) : totalRecord / Integer.parseInt(rows) + 1; // 计算总页数

		String[][] s = new String[list.size()][6];
		for (int i = 0; i < list.size(); i++) {
			Order order = list.get(i);
			s[i][0] = order.getOrderId().toString();
			s[i][1] = order.getTotalAmount().toString();
			s[i][2] = order.getStartDate().toString();
			s[i][3] = order.getEndDate().toString();
			s[i][4] = order.getStatus() + "";
			s[i][5] = order.getCreateTime().toString();

		}
		String[] title = new String[] { "id", "total_amount", "start_date", "end_date", "status", "create_time" };

		String mystring = grid.data2Jsonstring(totalRecord, page, totalPage, title, s);
		grid.stringToPage(response, mystring);

	}

	private String delete2(String id) {
		orderManager.deleteOrder(Long.parseLong(id));
		try {
			HttpServletResponse response = this.getResponse();
			PrintWriter out;
			out = response.getWriter();
			out.println("订单删除成功");
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}